package com.cloud.phone.websocket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.cloud.phone.base.BaseHandler;
import com.cloud.phone.constants.Constants;

import org.json.JSONObject;

import java.net.URI;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author : njb
 * @date : 2024/4/25 11:03
 * @desc : websocket通信的service
 */
public class WSService extends Service {

    private static final String TAG = WSService.class.getSimpleName();

    /**
     * 日志id
     */
    public static volatile int mLogId = 0;

    private WSClient mWSClient;


    /**
     * 链接的线程池
     */
    private ExecutorService mExecutorService;

    /**
     * mac地址
     */
    private String macAddress;

    /**
     * 监听的列表
     */
    private CopyOnWriteArrayList<WSPushMsgListener> mWSPushMsgListeners = new CopyOnWriteArrayList<>();

    /**
     * 实例
     */
    private static volatile WSService instance;


    private Messenger mMessenger;
    private String phoneId = "";

    /**
     * 获取实例
     *
     * @return service实例
     */
    public static WSService getInstance() {
        return instance;
    }


    public List<WSPushMsgListener> getWSPushMsgListeners() {
        return mWSPushMsgListeners;
    }

    /**
     * 添加监听
     *
     * @param listener
     */
    public void addWSPushMsgListener(WSPushMsgListener listener) {
        if (listener == null) {
            return;
        }
        if (!mWSPushMsgListeners.contains(listener)) {
            mWSPushMsgListeners.add(listener);
        }
    }

    /**
     * 移除监听
     *
     * @param listener
     */
    public void removeWSPushMsgListener(WSPushMsgListener listener) {
        if (mWSPushMsgListeners != null && listener != null && mWSPushMsgListeners.contains(listener)) {
            mWSPushMsgListeners.remove(listener);
        }
    }

    private BaseHandler<WSService> mHandler = new BaseHandler<>(this, new BaseHandler.BaseHandlerCallBack() {
        @Override
        public void callBack(Message msg) {
            switch (msg.what) {
                case Constants.WHAT_CONNECT_OPEN: //连接成功后发送MAC地址给服务器记录
                    try {
                        mWSClient.send("");
                        mHandler.sendEmptyMessageDelayed(Constants.WHAT_LIVE, 2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                        LogUtils.d(TAG, "连接成功后发送MAC地址给服务器记录失败" + e);
                    }
                    // 监听消息
                    for (WSPushMsgListener listener : mWSPushMsgListeners) {
                        listener.onReceivedMsg("connectSuccess", "");
                    }
                    break;
                case Constants.WHAT_HANDLE_RECEIVED_MSG: // 接收的消息
                    // 处理日志id和type
                    String type = "";
                    try {
                        JSONObject jsonObject = new JSONObject((String) msg.obj);
                        String data = jsonObject.optString("data");
                        type = jsonObject.optString("type");
                        if (!TextUtils.isEmpty(data)) {
                            JSONObject jsonObjectData = jsonObject.optJSONObject(data);
                            mLogId = jsonObjectData.optInt("log_id", 0);
                        } else {
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    LogUtils.d(TAG, "接收推送消息内容 type = " + type + " message = " + (String) msg.obj + " " + mWSPushMsgListeners.size());
                    // 监听消息
                    for (WSPushMsgListener listener : mWSPushMsgListeners) {
                        listener.onReceivedMsg(type, (String) msg.obj);
                    }
                    break;
                case Constants.WHAT_REMOTE_INTERRUPT: //远程主动断开连接
                    LogUtils.d(TAG, "远程主动断开连接");
                    mHandler.removeMessages(Constants.WHAT_LIVE);
                    connectWebSocket();
                    break;
                case Constants.WHAT_LOCAL_INTERRUPT: //本地断开连接了
                    LogUtils.d(TAG, "本地断开连接了");
                    mHandler.removeMessages(Constants.WHAT_LIVE);
                    connectWebSocket();
                    break;
                case Constants.WHAT_FETCHING_LOG_ID:
                    LogUtils.d(TAG, "获取日志ID");
                    try {
                        if (msg.replyTo != null) {
                            Message message = new Message();
                            message.obj = mLogId;
                            msg.replyTo.send(message);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                case Constants.WHAT_LIVE:
                    try {
                        LogUtils.d(TAG, "callBack:发送心跳包 - socket = " + Constants.BASE_REMOTE_WS_PREFIX);
                        isActive = true;
                        mWSClient.send("{\"type\":\"ping\"}");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessageDelayed(Constants.WHAT_LIVE, Constants.WHAT_LIVE_TIME);
                default:
                    break;
            }
        }
    });

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mExecutorService = Executors.newFixedThreadPool(1);
        initSocket();
        LogUtils.d(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String deviceMacAddress = intent.getStringExtra(Constants.DEVICE_MAC_ADDRESS);
            if (!TextUtils.isEmpty(deviceMacAddress)) {
                macAddress = deviceMacAddress;
            }
        }
        LogUtils.d(TAG, "onStartCommand macAddress = " + macAddress);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        phoneId = intent.getStringExtra("phoneId");
        return null;
    }

    /**
     * 初始化socket
     */
    public void initSocket() {
        LogUtils.d(TAG, "初始化socket");
        connectWebSocket();
    }



    /**
     * 连接websocket
     */
    private void connectWebSocket() {
        try{
            mWSClient = new WSClient(mHandler, URI.create(URLEncoder.encode(WebsocketUtil.getWebsocketUtil().currentWebSocketUrl)));
            mWSClient.setWsClientListener(() -> {
                isActive = false;
            });
            mExecutorService.execute(() -> {
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mWSClient.connect();
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "WSService onDestroy");
        if (mExecutorService != null) {
            mExecutorService.shutdown();
        }
        if (mHandler != null) {
            mHandler.destroy();
        }
        if (mWSPushMsgListeners != null) {
            mWSPushMsgListeners.clear();
        }
    }


    private volatile boolean isActive = false;

    public boolean getIsActive() {
        return isActive;
    }
}
